package pkg

import (
	"day15/app_config"
	"github.com/qiniu/go-sdk/v7/auth"
	"github.com/qiniu/go-sdk/v7/storage"
	"mime/multipart"
)

func FileUpload(file multipart.File, size int64) (string, error) {
	bucket := "badaoge" //空间名字
	putPolicy := storage.PutPolicy{
		Scope: bucket,
	}
	accessKey := app_config.AppConf.QiNiuConfig.Ak
	secretKey := app_config.AppConf.QiNiuConfig.Sk
	mac := auth.New(accessKey, secretKey)
	upToken := putPolicy.UploadToken(mac)

	cfg := storage.Config{}
	// 空间对应的机房
	cfg.Region = &storage.ZoneHuadong
	// 是否使用https域名
	cfg.UseHTTPS = false
	// 上传是否使用CDN上传加速
	cfg.UseCdnDomains = false

	// 构建表单上传的对象
	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}

	// 可选配置
	putExtra := storage.PutExtra{
		Params: map[string]string{
			"x:name": "github logo",
		},
	}
	err := formUploader.PutWithoutKey(nil, &ret, upToken, file, size, &putExtra)
	if err != nil {
		return "", err
	}
	imgHost := "http://sfcrh5w6m.hd-bkt.clouddn.com/"
	imgUrl := imgHost + ret.Key
	return imgUrl, nil

}
